<template>
    <div>
        <el-upload
            class="upload-file"
            :action="uploadFileUrl"
            :on-remove="handleRemove"
            :file-list="defaultFileList"
            :list-type="ListType"
            :on-success="handleFilesSuccess"
            :before-upload="beforeilesUpload"
            :on-preview="onPreview"
            :headers="headers"
            :disabled="disabled"
        >
            <el-button v-if="disabled === false" size="small" type="primary">点击上传</el-button>
            <div v-if="showTip && disabled === false" slot="tip" class="el-upload__tip">
                {{ fileTip }}
            </div>
        </el-upload>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
    name: "FileList",
    props: {
        // 文件上传地址
        // fileUploadUrl: {
        //     type: String,
        //     default: defaultFileUploadUrl,
        // },
        // 单个图片大小限制
        fileSize: {
            type: Number,
            default: 5,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        // 自定义Headers
        // headers: {
        //     type: Object,
        //     default: () => ({
        //         Authorization: token, // 让每个请求携带自定义token 请根据实际
        //     }),
        // },
        // 列表类型：text/picture/picture-card
        ListType: {
            type: String,
            default: "picture",
        },
        // 是否显示提示
        showTip: {
            type: Boolean,
            default: true,
        },
        // 图片列表 必须得传
        value: {
            type: Array,
            require: false,
            default: () => new Array(),
        },
    },
    model: {
        prop: "value",
        event: "change",
    },
    data() {
        return {
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            defaultFileList: this.value,
        };
    },
    created() {},
    computed: {
        isPicture() {
            let flag =
                this.ListType &&
                (this.ListType === "picture" ||
                    this.ListType === "picture-card");
            return flag;
        },
        fileTip() {
            let flag =
                this.ListType &&
                (this.ListType === "picture" ||
                    this.ListType === "picture-card");
            let message =
                flag === true
                    ? `只能上传图片，且单文件不能超过 ${this.fileSize}M`
                    : `单文件不能超过 ${this.fileSize}M`;
            return message;
        },
    },
    methods: {
        // 移除图片
        handleRemove(file, fileList) {
            this.defaultFileList = fileList.slice(0);
            this.$emit("change", this.defaultFileList);
        },
        // 图片上传成功
        handleFilesSuccess(res, file) {
            let fileListTemp = [...this.defaultFileList];
            if (res.code === 200) {
                // this.form.concreteSiteIcon = data.fileUrl;
                let fileObj = {
                    // id: res.data.id,
                    name: res.data.fileName,
                    uri: res.data.uri,
                    url: res.data.url,
                };
                fileListTemp.push(fileObj);
            } else if (res.code === 500) {
                this.msgError("系统错误，上传失败");
            } else {
                this.megError(res.msg);
            }
            this.defaultFileList = fileListTemp.slice(0);
            // 让v-model绑定的值变
            this.$emit("change", this.defaultFileList);
        },
        // 文件上传之前校验和过滤
        beforeilesUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < this.fileSize;
            // let isAccept = new RegExp("image/*").test(file.type);
            if (
                this.ListType &&
                (this.ListType === "picture" ||
                    this.ListType === "picture-card")
            ) {
                // if (!isAccept) {
                //     this.msgError("应该选择image/*类型的文件");
                // }
            }
            if (!isLt2M) {
                this.msgError(`上传头像图片大小不能超过 ${this.fileSize}MB!`);
            }
            return isLt2M;
        },
        onPreview(file) {
            this.downloadUrlFile(file.url, file.name);
            // return false;
        },

        // 保存到本地并自动点击
        saveAs(data, name) {
            const urlObject = window.URL || window.webkitURL || window;
            const export_blob = new Blob([data]);
            const save_link = document.createElementNS(
                "http://www.w3.org/1999/xhtml",
                "a"
            );
            save_link.href = urlObject.createObjectURL(export_blob);
            save_link.download = name;
            save_link.click();
        },
        // 下载含有url的文件
        downloadUrlFile(url, fileName) {
            const url2 = url.replace(/\\/g, "/");
            const xhr = new XMLHttpRequest();
            xhr.open("GET", url2, true);
            xhr.responseType = "blob";
            //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
            // 为了避免大文件影响用户体验，建议加loading
            xhr.onload = () => {
                if (xhr.status === 200) {
                    // 获取文件blob数据并保存
                    this.saveAs(xhr.response, fileName);
                }
            };
            xhr.send();
        },
    },
    watch: {
        value: function (newV, oldV) {
            this.defaultFileList = newV;
        },
    },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
    margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
}
.upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
}
.ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
}
</style>
